<template>
<el-container class="guanggao">
  <back></back>
  <el-main>
    <div class="top">
      <h5>云商汇平台广告推广服务购买</h5>
    </div>
    <div class="upload">
      <p>请上传广告图片(最佳分辨率768*500)</p>
      <el-upload
        class="avatar-uploader"
        :action="uploadUrl"
        :show-file-list="false"
        :http-request="uploadZhiZhao"

        :data="options"
        >
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
      <b class="tip">温馨提示:广告一旦购买成功，广告图片不可以修改，不可以退费，请核实图片无误后支付订单</b>
    </div>
    <div class="position">
      <p>投放位置</p>
     <el-radio-group v-model="positionTf">
       <el-radio @change="isIndex" label="首页">首页 <i style="color: red;font-size: 12px;margin-left: 3px">(剩余{{this.surplus}}位置)</i></el-radio>
       <el-radio @change="isClick(item.itemName,item.itemLevel,item.itemId)" v-for="item in list" :label="item.itemName" :key="item.itemId">{{item.parentName +'-'+item.itemName}} <i style="color: red;font-size: 12px;margin-left: 3px">(剩余{{item.freeCount}}位置)</i></el-radio>
     </el-radio-group>
    </div>
    <div class="time">
      <p>投放时间</p>
      <el-radio-group v-model="timeTf">
        <el-radio v-if="chooseIndex == 1" v-for="item in timeButtonList.slice(0,3)" @change="chooseTime(item.amount,item.location,item.duration)" :key="item.id" :label="item.amount">{{item.name}}</el-radio>
        <el-radio v-if="chooseIndex == 0" v-for="item in timeButtonList.slice(-3)" @change="chooseTime(item.amount,item.location,item.duration)" :key="item.id" :label="item.amount">{{item.name}}</el-radio>
      </el-radio-group>
    </div>
    <div class="tip">
      <p>
        购买后立即生效，到期后将会下架广告，如有需要，请及时购买
      </p>
    </div>
  </el-main>
  <el-footer>
    <span><i class="iconfont icon-iconmoney"></i><b>{{this.timeTf}}</b></span>
    <span class="pay" @click="pay">支付</span>
  </el-footer>
</el-container>
</template>

<script>
  import back from '@/components/back'
  import qs from 'qs'
    export default {
      data(){
        return{
          dialogImageUrl: '',
          dialogVisible: false,
          positionTf:'',
          timeTf:'',
          money:'',
          timeButtonList:[],
          options:{

          },
          uploadUrl:'/api/front/merchantInfo/upload',//上传图片的远程仓库地址
          imageUrl:'',
          imageId:'',
          list:[],
          surplus:'',//首页剩余
          location:'',
          duration:'',
          itemId:'',
          levelId:'',
          data:[],
          upImg:false,//判断图片是否被点击
          chooseIndex:1,//0 不是选择首页,1选择首页
          userId:'',

        }
      },
      methods:{
        isIndex(val){
          this.chooseIndex = 1;
          this.positionTf = val;
          console.log(this.chooseIndex)
        },
        onBridgeReady(){
          let that = this;
          WeixinJSBridge.invoke(
            'getBrandWCPayRequest',{
              "appId":this.data.appId,     //公众号名称，由商户传入
              "timeStamp":this.data.timeStamp,         //时间戳，自1970年以来的秒数
              "nonceStr":this.data.nonceStr, //随机串
              "package":this.data.package,
              "signType":this.data.signType,         //微信签名方式：
              "paySign":this.data.paySign //微信签名
            },
            function (res) {
              if(res.err_msg === "get_brand_wcpay_request:ok" ){
                that.$message.success('支付成功')
                that.$router.push('/indexs')
                // 使用以上方式判断前端返回,微信团队郑重提示：
                //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
              }else if (res.err_msg === 'get_brand_wcpay_request:fail') {
                that.$message.error('网络异常，请重试')
              }
            });
        },
        pay(){
          if(this.upImg == false){
            this.$message.warning('请选择上传图片');
            return;
          }
          if(this.positionTf == '' ){
            this.$message.warning('请选择投放位置');
            return;
          }
          if(this.timeTf == ''){
            this.$message.warning('请选择投放时间');
            return;
          }
          let position = '';
         if(this.positionTf == '首页'){
            position = 0
         }
         else {
           position = 1
         };
         //完善广告图片信息
          let uploadImg = {
            merchantId:this.userId,
            photoId:this.imageId,
            // location:this.positionTf == '首页' ? 0 : 1
            location:position,
            itemId:this.itemId
          };
         console.log(uploadImg,"上传图片参数");
          let openid = localStorage.getItem('openId');
          let that = this;
          this.$axios.post('/api/front/merchantInfo/infoPhoto',qs.stringify(uploadImg))
            .then(res => {
              if(res.data.status == 200){
                let params = {
                  merchantId:that.userId,
                  amount:this.timeTf,
                  // amount:0.01,
                  openId:openid,
                  location:that.location,
                  duration:that.duration,
                  levelId:that.levelId,
                  itemId:that.itemId,
                  photoId:that.imageId,
                };
                console.log(params,'支付')
                that.$axios.post('api/front/wxpay/getCodeForAd',that.qs.stringify(params))
                  .then(res => {
                    that.data = res.data.obj;
                    if (typeof WeixinJSBridge == "undefined"){
                      if( document.addEventListener ){
                        document.addEventListener('WeixinJSBridgeReady', that.onBridgeReady(), false);
                      }else if (document.attachEvent){
                        document.attachEvent('WeixinJSBridgeReady', that.onBridgeReady());
                        document.attachEvent('onWeixinJSBridgeReady', that.onBridgeReady());
                      }
                    }else{
                      that.onBridgeReady();
                    }
                  });

              }
              else {
                this.$message.error('当前用户访问过多，请稍后重试！');
              }
            })

        },
        chooseType(event,file,fileList){
          console.log(event,file,fileList)
        },
        isClick(name,itemLevel,itemId){
          this.chooseIndex = 0;
          this.positionTf = name;
          this.itemId = itemId;
          this.levelId = itemLevel;
          console.log(this.chooseIndex,name,itemLevel,itemId)
        },
        chooseTime(money,position,duration){
          this.timeTf = money
          this.location = position;
          this.duration = duration
          console.log(this.timeTf,this.location)
        },
        uploadZhiZhao(params){
          let form = new FormData();
          form.append('file',params.file);
          form.append('type',4);
          form.append('merchantId',this.userId)
          let that = this;
          this.$axios.post(params.action,form)
            .then(res => {
              that.imageUrl = res.data.obj.url;
              that.imageId = res.data.obj.photoId;
              that.upImg = true;
              console.log('success',res.data)
            })
        },

      },
      computed:{
        userId(){
          return this.$store.state.merchantId
        }
      },
      created(){
        this.userId = localStorage.getItem("merchantId");
        this.$axios.post('/api/front/merchantInfo/index_free')
          .then(res => {
            this.surplus = res.data.obj;
          })
          let params = {
          merchantId:this.userId
        };

        this.$axios.post('/api/front/item/listByMerchantId',this.qs.stringify(params))
          .then(res => {
            this.list = res.data.obj;
            console.log(this.list)
          })
      },
      mounted(){
        this.$axios.post('/api/front/costItem/advertisement')
          .then(res => {
            this.timeButtonList = res.data.obj;
            // console.log(this.timeButtonList.slice(0,3))
            // console.log(this.timeButtonList.slice(-3))

          })
      },
      components:{
        back,
      }
    }
</script>

<style scoped lang="scss">
.el-container{
  display: flex;
  flex-direction: column;
  height: 100%;
  .el-main{
    .top{
      h5{
        font-size: 16px;
      }
    }
    .upload{
      border-bottom: 1px solid #f2f2f2;
      p{
        font-size: 15px;
        text-align: left;
        padding-left: 15px;
      }
      b.tip{
        padding: 15px 0;
        display: inline-block;
        color: red;
        padding-left: 15px;
        text-align: left;
        font-size: 14px;
      }
    }
    .position{
      padding: 15px 0;
      border-bottom: 1px solid #f2f2f2;
      p{
        text-align: left;
        padding-left: 15px;
        font-size: 14px;
      }
      .el-radio-group{
        display: flex;
        flex-direction: column;
        .el-radio{
          text-align: left;
          padding-left: 15px;
          margin: 5px 0;
        }
      }
    }
    .time{
      padding-bottom:20px ;
      border-bottom: 1px solid #DCDFE6;
      p{
        text-align: left;
        padding-left: 15px;
        font-size: 14px;
      }
      .el-radio-group{
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        padding: 0 15px;
        .el-radio{
          width: 50%;
          text-align: left;
          margin-bottom: 5px;
        }
      }

    }
    .tip{
      p{
        padding:20px 0 40px 15px;
        font-size: 14px;
        text-align: left;
      }
    }
  }
  .el-footer{
    display: flex;
    flex-direction: row;
    border-top: 1px solid #f1f1f1;
    box-shadow: 0px -1px 10px #ccc;
    padding: 0;
    padding-bottom: 10px;
    span{
      display: flex;
      flex-direction: row;
      padding: 10px 0;
      color: red;
      &:nth-child(1){
        width: 60%;
        display: inline-block;
        text-align: right;
        padding-right: 30px;
        i{
          font-size: 13px;
          font-weight: normal;
        }
        b{
          font-size: 20px;
        }
      }
      &:nth-child(2){
        display: inline-block;
        width: 40%;
        text-align: center;
        background: red;
        color: #fff;
        font-size: 16px;
      }
    }
  }
}
</style>
